package morphage.engine;

import no.uib.cipr.matrix.DenseMatrix;

import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import java.awt.image.Raster;

public class MatrixBufferedImage extends BufferedImage
{
  public DenseMatrix    m_matLum;
  public DenseMatrix    m_matR, m_matG, m_matB;
  
  public MatrixBufferedImage(int width, int height, int type)
  {
    super(width, height, type);
    m_matLum = new DenseMatrix(width, height);
  }
  public MatrixBufferedImage(BufferedImage image)
  {
    super(image.getWidth(), image.getHeight(), image.getType());
    image.copyData(this.getRaster());
    m_matLum = new DenseMatrix(image.getWidth(), image.getHeight());
  }
  
  public void image2Matrix()
  {
    assert( this.getType() == BufferedImage.TYPE_INT_RGB );
    Raster raster = this.getData();
    DataBufferInt buf = (DataBufferInt)raster.getDataBuffer();
    int[]     imageData = buf.getData();
    double[]  matrixData = m_matLum.getData();
    Pixel pixel = new Pixel();
    int size = m_matLum.numRows() * m_matLum.numColumns();
    for( int i=0; i<size; ++i )
    {
      pixel.setColor( imageData[ i ] );
      matrixData[ i ] = (double)pixel.lum();
    }
  }
  public void matrix2Image()
  {
    Raster raster = this.getData();
    DataBufferInt buf = (DataBufferInt)raster.getDataBuffer();
    int[]     imageData = buf.getData();
    double[]  matrixData = m_matLum.getData();
    Pixel pixel = new Pixel();
    int size = m_matLum.numRows() * m_matLum.numColumns();
    for( int i=0; i<size; ++i )
    {
      pixel.setLum( (float)matrixData[ i ] );
      imageData[ i ] = pixel.getIntColor();
    }
    this.setData( raster );
  }
}
